package io.kiki.sba.registry.common.model;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.Objects;

@Setter
@Getter
public final class RegisterVersion implements Serializable, Comparable<RegisterVersion> {
    private final long version;
    private final long registerTimestamp;

    public RegisterVersion(long version, long registerTimestamp) {
        this.version = version;
        this.registerTimestamp = registerTimestamp;
    }

    public static RegisterVersion of(long version, long registerTimestamp) {
        return new RegisterVersion(version, registerTimestamp);
    }


    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (!(o instanceof RegisterVersion))
            return false;
        RegisterVersion that = (RegisterVersion) o;
        return version == that.version && registerTimestamp == that.registerTimestamp;
    }

    @Override
    public int hashCode() {
        return Objects.hash(version, registerTimestamp);
    }

    @Override
    public int compareTo(RegisterVersion o) {
        if (version < o.version) {
            return -1;
        }
        if (version > o.version) {
            return 1;
        }

        if (registerTimestamp < o.registerTimestamp) {
            return -1;
        }
        if (registerTimestamp > o.registerTimestamp) {
            return 1;
        }
        return 0;
    }

    public boolean orderThan(RegisterVersion o) {
        return compareTo(o) < 0;
    }


    public RegisterVersion incrRegisterTimestamp() {
        return RegisterVersion.of(this.version, this.registerTimestamp + 1);
    }
}
